package cn.xspace.wnx.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BBizList;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.location.LocationInfoBean;
import com.xspace.android.xafcommon.location.LocationResult;
import com.xspace.android.xafcommon.location.MyAMapLocation;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.T;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.entity.AreaBean;
import cn.xspace.wnx.entity.ServiceObjBean;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ServiceObjModifyActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private RelativeLayout mRlObjectType;
    private TextView mTvObjectTypeName;
    private EditText mEtUserName;
    private EditText mEtUserMobile;
    private EditText mEtOrgName;
    private TextView mTvOrgStar;
    private RelativeLayout mRlFeedType;
    private TextView mTvFeedType;
    private RelativeLayout mRlDistrict;
    private TextView mTvDistrict;
    private RelativeLayout mRlTowns;
    private TextView mTvTowns;
    private RelativeLayout mRlVillages;
    private TextView mTvVillages;
    private RelativeLayout mRlShe;
    private TextView mTvSheName;
    private RelativeLayout mRelativeLocation;
    private RelativeLayout mLongitude;
    private RelativeLayout mLatitude;
    private TextView mTvLocation;
    private TextView longitude;
    private TextView latitude;
    private RelativeLayout mRlNjName;
    private TextView mTvNjName;
    private RadioGroup mRgShengTai;
    private RadioButton mRbShengTaiYes;
    private RadioButton mRbShengTaiNo;
    private LinearLayout mLayoutFeedInfo;
    private Button mAddFeedInfo;

    private List<ServiceObjBean> mTypeList;
    private List<ServiceObjBean> mBreedCodeList;
    private List<ServiceObjBean> mAnimalDoctorList;
    private List<AreaBean> mTownsList;
    private double textLatitude;
    private double textLongitude;

    private ListView mBizListView;
    private ArrayAdapter<BBizList> adapter;
    private ArrayList<BBizList> animalInfoList = new ArrayList<>();

    //是否是编辑信息,默认添加信息
    private boolean isEditInfo;
    private ServiceObjBean serviceObjBean;

    private String user_id;
    private String plat_code;
    private String user_areacode;

    private AlertDialog alertDialog;
    private boolean isLocationSuccess = false;
    private boolean chooseSanyang;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(mContext);
        startLocation();
    }

    @Override
    protected void getIntentData() {
        isEditInfo = getIntent().getBooleanExtra(IntentConstant.isEditInfo, false);
        if (!isEditInfo) {
            serviceObjBean = new ServiceObjBean();
        } else {
            serviceObjBean = (ServiceObjBean) getIntent().getSerializableExtra(IntentConstant.serviceObjBean);
            chooseSanyang = Type.PersonOrOrg.PERSON.equals(serviceObjBean.user_type);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_service_obj_modify);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        if (isEditInfo) { //编辑服务对象
            mTitleBar.setTitle(getString(R.string.edit_service_obj));
        } else { //新增服务对象
            mTitleBar.setTitle(getString(R.string.add_service_obj));
        }
        mRlObjectType = (RelativeLayout) findViewById(R.id.rl_service_obj_type);
        mTvObjectTypeName = (TextView) findViewById(R.id.tv_service_obj_type);
        ImageView arrowType = (ImageView) findViewById(R.id.arrow_service_obj_type);
        mEtUserName = (EditText) findViewById(R.id.et_charge_name);
        mEtUserMobile = (EditText) findViewById(R.id.et_charge_phone);
        mEtOrgName = (EditText) findViewById(R.id.et_org_name);
        mTvOrgStar = (TextView) findViewById(R.id.tv_service_obj_org_star); //机构必填的红色星号
//        if (isEditInfo) { //编辑模式下不能修改类型手机号等
//            mEtUserName.setKeyListener(null);
//            mEtUserMobile.setKeyListener(null);
//            mEtOrgName.setKeyListener(null);
//        }
        mRlFeedType = (RelativeLayout) findViewById(R.id.rl_feed_type);
        mTvFeedType = (TextView) findViewById(R.id.txt_feed_type);
        mRlDistrict = (RelativeLayout) findViewById(R.id.rl_edit_area_country);
        mTvDistrict = (TextView) findViewById(R.id.txt_edit_country);
        mRlTowns = (RelativeLayout) findViewById(R.id.rl_towns);
        mTvTowns = (TextView) findViewById(R.id.txt_in_towns);
        mRlVillages = (RelativeLayout) findViewById(R.id.rl_villages);
        mTvVillages = (TextView) findViewById(R.id.txt_edit_in_villages);
        mRlShe = (RelativeLayout) findViewById(R.id.rl_she);
        mTvSheName = (TextView) findViewById(R.id.txt_in_agency);
        mRelativeLocation = (RelativeLayout) findViewById(R.id.relative_location_address);
        mLongitude = (RelativeLayout) findViewById(R.id.relative_longitude);
        mLatitude = (RelativeLayout) findViewById(R.id.relative_latitude);
        mTvLocation = (TextView) findViewById(R.id.txt_location);
        longitude = (TextView) findViewById(R.id.txt_longitude);
        latitude = (TextView) findViewById(R.id.txt_latitude);
        mRlNjName = (RelativeLayout) findViewById(R.id.rl_service_obj_nj);
        mTvNjName = (TextView) findViewById(R.id.tv_service_obj_nj);
        ImageView arrowNj = (ImageView) findViewById(R.id.arrow_service_obj_nj);
        mBizListView = (ListView) findViewById(R.id.lv_biz_list);
        mLayoutFeedInfo = (LinearLayout) findViewById(R.id.layout_feed_info);
        mAddFeedInfo = (Button) findViewById(R.id.add_feed_info);
        mRgShengTai = (RadioGroup) findViewById(R.id.rg_shengtaiflag);
        mRbShengTaiYes = (RadioButton) findViewById(R.id.rb_shengtaiflag_yes);
        mRbShengTaiNo = (RadioButton) findViewById(R.id.rb_shengtaiflag_no);
        if (isEditInfo) {
            arrowType.setVisibility(View.GONE);
            arrowNj.setVisibility(View.GONE);
            fillView();
            changeSanyangStyle();
        } else {
            mRbShengTaiNo.setChecked(true);//生态巡检默认选择否
            serviceObjBean.shengtai_flag = "0";
        }
    }

    private void fillView() {
        if (serviceObjBean != null) {
            mTvObjectTypeName.setText(serviceObjBean.object_typename);
            mEtUserName.setText(serviceObjBean.user_name);
            mEtUserMobile.setText(serviceObjBean.user_mobile);
            mEtOrgName.setText(serviceObjBean.factory_name);
            mTvFeedType.setText(serviceObjBean.breed_codename);
            //生态养殖
            if (!TextUtils.isEmpty(serviceObjBean.shengtai_flag)) {
                if ("0".equals(serviceObjBean.shengtai_flag)) {
                    mRbShengTaiNo.setChecked(true);
                } else if ("1".equals(serviceObjBean.shengtai_flag)) {
                    mRbShengTaiYes.setChecked(true);
                }
            }
            mTvDistrict.setText(serviceObjBean.user_quname);
            mTvTowns.setText(serviceObjBean.user_zhenname);
            mTvVillages.setText(serviceObjBean.user_cunname);
            mTvSheName.setText(serviceObjBean.user_shename);
            latitude.setText(serviceObjBean.latitude);
            longitude.setText(serviceObjBean.longitude);
            mTvNjName.setText(serviceObjBean.nj_username);
            animalInfoList.addAll(serviceObjBean.bizList);
            fillBizView();
        }
    }

    private void fillBizView() {
        if (animalInfoList.size() > 0) {
            mLayoutFeedInfo.setVisibility(View.VISIBLE);
        } else {
            mLayoutFeedInfo.setVisibility(View.GONE);
        }
        if (adapter == null) {
            adapter = new ArrayAdapter<BBizList>(mContext, R.layout.animal_use_item, animalInfoList) {
                @NonNull
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    BBizList item = animalInfoList.get(position);
                    if (convertView == null) {
                        convertView = View.inflate(mContext, R.layout.animal_use_item, null);
                    }
                    TextView animalName = (TextView) convertView.findViewById(R.id.animal_name);
                    TextView animalUse = (TextView) convertView.findViewById(R.id.animal_use);
                    TextView animalCount = (TextView) convertView.findViewById(R.id.animal_count);
                    animalName.setText(checkNull(item.biz_name));
                    animalUse.setText(checkNull(item.animal_use_name));
                    animalCount.setText(checkNull(item.animal_count));
                    return convertView;
                }
            };
            mBizListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private String checkNull(String string) {
        if (TextUtils.isEmpty(string) || string.contains("null")) {
            return "";
        } else {
            return string;
        }
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        plat_code = MyInfoUtil.getPlatCode();
        user_areacode = MyInfoUtil.getAppDeptAreaCode();
        requestBaseData();
    }

    private void requestBaseData() {
        requestAreaData();
        if (!isEditInfo) {
            requestBreedCode(true);
            requestServiceObjType(true);
        }
    }

    private void requestAreaData() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("area_code", user_areacode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_AREA_DETAIL, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseReturnBean bean) {
                        try {
                            JSONObject jsonObject = new JSONObject(bean.data);
                            if (!isEditInfo) {
                                serviceObjBean.user_quname = jsonObject.optString("area_name");
                                serviceObjBean.user_qucode = jsonObject.optString("area_code");
                                mTvDistrict.setText(serviceObjBean.user_quname);
                                mTvTowns.setText(R.string.please_select);
                            }
                            requestTownsList(true);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void requestTownsList(final boolean isFirstIn) {
        hideWaitDialog();
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        String query_plat = "common";
        map.put("query_plat", query_plat);
        map.put("area_code", serviceObjBean.user_qucode); //该id为空时进不了该方法
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_AREA, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<AreaBean>>() {
                    @Override
                    public List<AreaBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<AreaBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AreaBean>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<AreaBean> newList) {
                        hideWaitDialog();
                        mTownsList = new ArrayList<>();
                        mTownsList.addAll(newList);
                        if (!isFirstIn) {
                            showTownsDialog();
                        }
                    }
                });
    }

    private void requestServiceObjType(final boolean isFirstIn) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("plat_code", plat_code);
        map.put("user_areacode", user_areacode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_SERVICE_OBJ_TYPE, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<ServiceObjBean>>() {
                    @Override
                    public List<ServiceObjBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<ServiceObjBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ServiceObjBean>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<ServiceObjBean> newList) {
                        hideWaitDialog();
                        mTypeList = new ArrayList<>();
                        mTypeList.addAll(newList);
                        if (isFirstIn) {
                            //设置初始值
                            if (mTypeList.size() > 0) {
                                mTvObjectTypeName.setText(mTypeList.get(0).object_typename);
                                serviceObjBean.object_code = mTypeList.get(0).object_code;
                                serviceObjBean.object_type = mTypeList.get(0).object_type;
                                serviceObjBean.object_typename = mTypeList.get(0).object_typename;
                            }
                        } else {
                            showTypeSelectDialog();
                        }
                    }
                });
    }

    private void requestBreedCode(final boolean isFirstIn) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("plat_code", plat_code);
        map.put("user_areacode", user_areacode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_BREEDCODE, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<ServiceObjBean>>() {
                    @Override
                    public List<ServiceObjBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<ServiceObjBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ServiceObjBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<ServiceObjBean> newList) {
                        hideWaitDialog();
                        mBreedCodeList = new ArrayList<>();
                        mBreedCodeList.addAll(newList);
                        if (isFirstIn) {
                            if (mBreedCodeList.size() > 0) {
                                mTvFeedType.setText(mBreedCodeList.get(0).breed_codename);
                                serviceObjBean.breed_code = mBreedCodeList.get(0).breed_code;
                                serviceObjBean.breed_codename = mBreedCodeList.get(0).breed_codename;
                            }
                        } else {
                            showBreedCodeDialog();
                        }
                    }
                });
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkSubmitData()) {
                    requestNetWork();
                }
            }
        });
        //服务对象类型列表
        mRlObjectType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isEditInfo) { //编辑模式不可选
                    if (mTypeList == null) {
                        requestServiceObjType(false);
                    } else {
                        showTypeSelectDialog();
                    }
                }
            }
        });
        //养殖类型列表
        mRlFeedType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBreedCodeList == null) {
                    requestBreedCode(false);
                } else {
                    showBreedCodeDialog();
                }
            }
        });
        //生态创建巡检
        mRgShengTai.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_shengtaiflag_yes) {
                    mRbShengTaiYes.setChecked(true);
                    serviceObjBean.shengtai_flag = "1";
                } else {
                    mRbShengTaiNo.setChecked(true);
                    serviceObjBean.shengtai_flag = "0";
                }
            }
        });
        //包片兽医员列表
        mRlNjName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEditInfo) {
                    if (mAnimalDoctorList == null) {
                        requestAnimalDoctor();
                    } else {
                        showAnimalDoctorDialog();
                    }
                }
            }
        });
        //地区选择框,其实只有一个可选择的
        mRlDistrict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(serviceObjBean.user_qucode)) { //区域进入界面后就请求网络设置,基本不会为空
                    //如果进去时没网,需考虑没网络等情况,加此该逻辑
                    requestAreaData();
                } else {
                    showAreaDialog();
                }
            }
        });
        //乡镇
        mRlTowns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkTownsData()) { //区id为空,不能加载下一级
                    if (mTownsList == null) {
                        requestTownsList(false);
                    } else {
                        showTownsDialog();
                    }
                }
            }
        });
        //村
        mRlVillages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(serviceObjBean.user_zhencode)) { //乡镇不能为空
                    T.showSingleL(getString(R.string.please_select_xiangzhen));
                } else {
                    requestVillagesList();
                }
            }
        });
        //社
        mRlShe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(serviceObjBean.user_cuncode)) { //村不能为空
                    T.showSingleL(getString(R.string.please_select_cun));
                } else {
                    requestSheList();
                }
            }
        });
        //地理位置信息
        View.OnClickListener onMapLocation = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MapLocationSearchActivity.class);
                startActivity(intent);
            }
        };
        mRelativeLocation.setOnClickListener(onMapLocation);
//        mLatitude.setOnClickListener(onMapLocation);
//        mLongitude.setOnClickListener(onMapLocation);
        mBizListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, FeedInfoEditActivity.class);
                BBizList animalInfoBean = animalInfoList.get(position);
                intent.putExtra(IntentConstant.isEditInfo, true);
                intent.putExtra(IntentConstant.editPosition, position);
                intent.putExtra(IntentConstant.animalInfoBean, animalInfoBean);
                intent.putExtra(IntentConstant.breed_code, serviceObjBean.breed_code);
                intent.putExtra(IntentConstant.object_type, serviceObjBean.object_type);
                startActivity(intent);
            }
        });
        mAddFeedInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(serviceObjBean.object_type)) {
                    T.showSingleL(getString(R.string.please_select_service_type));
                    return;
                } else if (TextUtils.isEmpty(serviceObjBean.breed_code)) {
                    T.showSingleL(getString(R.string.please_select_feed_type));
                    return;
                }
                Intent intent = new Intent(mContext, FeedInfoEditActivity.class);
                intent.putExtra(IntentConstant.animalInfoBeanList, animalInfoList);
                intent.putExtra(IntentConstant.object_type, serviceObjBean.object_type);
                intent.putExtra(IntentConstant.breed_code, serviceObjBean.breed_code);
                startActivity(intent);
            }
        });
    }

    /**
     * 检查提交数据的完整性
     *
     * @return
     */
    private boolean checkSubmitData() {
        if (!checkCanAddFeedInfo()) { //服务对象类型和养殖类型检查
            return false;
        } else if (TextUtils.isEmpty(mEtUserName.getText().toString().trim())) {
            T.showSingleL(getString(R.string.service_obj_name_not_empty));
            return false;
        } else if (TextUtils.isEmpty(mEtUserMobile.getText().toString().trim())) {
            T.showSingleL(getString(R.string.service_obj_phone_not_empty));
            return false;
        } else if (!chooseSanyang && TextUtils.isEmpty(mEtOrgName.getText().toString().trim())) { //选择散养户之后就不再检测
            T.showSingleL(getString(R.string.service_obj_org_not_empty));
            return false;
        } else if (TextUtils.isEmpty(serviceObjBean.breed_code)) {
            T.showSingleL(getString(R.string.please_select_xunjian));
            return false;
        } else if (!checkTownsData()) {
            return false;
        } else if (TextUtils.isEmpty(serviceObjBean.nj_userid)) {
            T.showSingleL(getString(R.string.please_select_animal_doctor));
            return false;
        }
        return true;
    }

    private boolean checkCanAddFeedInfo() {
        if (TextUtils.isEmpty(serviceObjBean.object_type)) {
            T.showSingleL(getString(R.string.please_select_service_type));
            return false;
        } else if (TextUtils.isEmpty(serviceObjBean.breed_code)) {
            T.showSingleL(getString(R.string.please_select_feed_type));
            return false;
        }
        return true;
    }

    private boolean checkTownsData() {
        if (TextUtils.isEmpty(serviceObjBean.user_qucode)) { //区id为空,不能加载下一级
            T.showSingleL(getString(R.string.please_select_qu));
            return false;
        } else {
            return true;
        }
    }

    private void showTypeSelectDialog() {
        final String[] arrays = new String[mTypeList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = mTypeList.get(j).object_typename;
            if (TextUtils.equals(mTypeList.get(j).object_type, serviceObjBean.object_type)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvObjectTypeName.setText(arrays[which]);
                        String user_type = mTypeList.get(which).user_type;
                        serviceObjBean.object_code = mTypeList.get(which).object_code;
                        serviceObjBean.object_type = mTypeList.get(which).object_type;
                        serviceObjBean.object_typename = mTypeList.get(which).object_typename;
                        //散养户
                        chooseSanyang = Type.PersonOrOrg.PERSON.equals(user_type); //1表示为个人,表示选择的为散养户
                        changeSanyangStyle();
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void changeSanyangStyle() {
        mTvOrgStar.setVisibility(chooseSanyang ? View.GONE : View.VISIBLE);
    }

    private void showBreedCodeDialog() {
        final String[] arrays = new String[mBreedCodeList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = mBreedCodeList.get(j).breed_codename;
            if (TextUtils.equals(mBreedCodeList.get(j).breed_code, serviceObjBean.breed_code)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvFeedType.setText(arrays[which]);
                        serviceObjBean.breed_code = mBreedCodeList.get(which).breed_code;
                        serviceObjBean.breed_codename = mBreedCodeList.get(which).breed_codename;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void requestAnimalDoctor() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_ANIMAL_DOCTOR, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<ServiceObjBean>>() {
                    @Override
                    public List<ServiceObjBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<ServiceObjBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ServiceObjBean>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<ServiceObjBean> newList) {
                        hideWaitDialog();
                        mAnimalDoctorList = new ArrayList<>();
                        mAnimalDoctorList.addAll(newList);
                        showAnimalDoctorDialog();
                    }
                });
    }

    private void showAnimalDoctorDialog() {
        final String[] arrays = new String[mAnimalDoctorList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = mAnimalDoctorList.get(j).nj_username;
            if (TextUtils.equals(mAnimalDoctorList.get(j).nj_userid, serviceObjBean.nj_userid)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvNjName.setText(arrays[which]);
                        serviceObjBean.nj_userid = mAnimalDoctorList.get(which).nj_userid;
                        serviceObjBean.nj_username = mAnimalDoctorList.get(which).nj_username;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void showAreaDialog() {
        final String[] arrays = new String[1];
        arrays[0] = serviceObjBean.user_quname;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setSingleChoiceItems(arrays, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvDistrict.setText(arrays[which]);
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void showTownsDialog() {
        final String[] arrays = new String[mTownsList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = mTownsList.get(j).area_name;
            if (TextUtils.equals(mTownsList.get(j).area_code, serviceObjBean.user_zhencode)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final int finalIndex = index;
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (finalIndex == which) {
                            alertDialog.dismiss();
                            return;
                        }
                        mTvTowns.setText(arrays[which]);
                        serviceObjBean.user_zhencode = mTownsList.get(which).area_code;
                        serviceObjBean.user_zhenname = mTownsList.get(which).area_name;
                        mTvVillages.setText(R.string.please_select);
                        serviceObjBean.user_cuncode = null;
                        serviceObjBean.user_cunname = null;
                        mTvSheName.setText(R.string.please_select);
                        serviceObjBean.user_sheid = null;
                        serviceObjBean.user_shename = null;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void requestVillagesList() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        String query_plat = "common";
        map.put("query_plat", query_plat);
        map.put("area_code", serviceObjBean.user_zhencode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_AREA, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<AreaBean>>() {
                    @Override
                    public List<AreaBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<AreaBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AreaBean>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<AreaBean> newList) {
                        hideWaitDialog();
                        showVillagesDialog(newList);
                    }
                });
    }

    private void showVillagesDialog(final List<AreaBean> newList) {
        final String[] arrays = new String[newList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = newList.get(j).area_name;
            if (TextUtils.equals(newList.get(j).area_code, serviceObjBean.user_cuncode)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final int finalIndex = index;
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (finalIndex == which) {
                            alertDialog.dismiss();
                            return;
                        }
                        mTvVillages.setText(arrays[which]);
                        serviceObjBean.user_cuncode = newList.get(which).area_code;
                        serviceObjBean.user_cunname = newList.get(which).area_name;
                        mTvSheName.setText(R.string.please_select);
                        serviceObjBean.user_sheid = null;
                        serviceObjBean.user_shename = null;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void requestSheList() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("area_code", serviceObjBean.user_cuncode);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_SHE, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<AreaBean>>() {
                    @Override
                    public List<AreaBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<AreaBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AreaBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<AreaBean> newList) {
                        hideWaitDialog();
                        showSheDialog(newList);
                    }
                });
    }

    private void showSheDialog(final List<AreaBean> newList) {
        final String[] arrays = new String[newList.size()];
        int index = -1;
        for (int j = 0; j < arrays.length; j++) {
            arrays[j] = newList.get(j).she_name;
            if (TextUtils.equals(newList.get(j).she_id, serviceObjBean.user_sheid)) {
                index = j;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final int finalIndex = index;
        alertDialog = builder.setSingleChoiceItems(arrays, index,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (finalIndex == which) {
                            alertDialog.dismiss();
                            return;
                        }
                        mTvSheName.setText(arrays[which]);
                        serviceObjBean.user_sheid = newList.get(which).she_id;
                        serviceObjBean.user_shename = newList.get(which).she_name;
                        alertDialog.dismiss();
                    }
                }).show();
    }

    private void requestNetWork() {
        showWaitDialog();
        String url;
        if (isEditInfo) { //分为编辑信息和添加信息
            url = Constants.UPDATE_SERVICE_OBJ;
        } else {
            url = Constants.ADD_SERVICE_OBJ;
        }
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("login_user_id", user_id);
        requestMap.put("plat_code", plat_code);
        requestMap.put("platform", "android");
        requestMap.put("create_orgid", MyInfoUtil.getUserOrgId());
        if (isEditInfo) { //编辑时有该值
            requestMap.put("user_type", serviceObjBean.user_type);
            requestMap.put("serviceobj_id", serviceObjBean.serviceobj_id);
            requestMap.put("user_id", serviceObjBean.user_id); //编辑时才有的参数,添加时该参数也不会有值
            requestMap.put("factory_id", serviceObjBean.factoryid); //同上
        } else {
            requestMap.put("object_code", serviceObjBean.object_code); //这个参数只有添加时传递
        }
        saveEtData();
        //共有参数
        requestMap.put("user_name", serviceObjBean.user_name);
        requestMap.put("user_mobile", serviceObjBean.user_mobile);
        requestMap.put("factory_name", serviceObjBean.factory_name);

        requestMap.put("object_type", serviceObjBean.object_type);
        requestMap.put("breed_code", serviceObjBean.breed_code);
        requestMap.put("shengtai_flag", serviceObjBean.shengtai_flag);
        requestMap.put("user_qucode", serviceObjBean.user_qucode);
        requestMap.put("user_zhencode", serviceObjBean.user_zhencode);
        requestMap.put("user_cuncode", serviceObjBean.user_cuncode);
        requestMap.put("user_sheid", serviceObjBean.user_sheid);

        requestMap.put("latitude", serviceObjBean.latitude);
        requestMap.put("longitude", serviceObjBean.longitude);
//        requestMap.put("position_name", serviceObjBean.position_name); //TODO 切换传递地址,而非传递经纬度
        requestMap.put("nj_userid", serviceObjBean.nj_userid);
        if (animalInfoList != null) {
            requestMap.put("bizList", animalInfoList);
        }
        OkHttpManager.getInstance().commonRequest(url, requestMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showSingleL(e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        T.showSingleL(baseReturnBean.desc);
                        HashMap<String, Object> eventMap = new HashMap<>();
                        if (isEditInfo) {
                            eventMap.put(EventBusConstant.TYPE, EventBusConstant.SERVICE_OBJECT_EDIT_SUCCESS);
                            eventMap.put(EventBusConstant.ACTION_VALUE, serviceObjBean);
                        } else {
                            eventMap.put(EventBusConstant.TYPE, EventBusConstant.SERVICE_OBJECT_ADD_SUCCESS);
                        }
                        EventBus.getDefault().post(eventMap);
                        finish();
                    }
                });
    }

    /**
     * 将EditText中的内容存到bean中
     */
    private void saveEtData() {
        serviceObjBean.user_name = mEtUserName.getText().toString().trim();
        serviceObjBean.user_mobile = mEtUserMobile.getText().toString().trim();
        serviceObjBean.factory_name = mEtOrgName.getText().toString().trim();
        serviceObjBean.latitude = String.valueOf(textLatitude);
        serviceObjBean.longitude = String.valueOf(textLongitude);
        if (serviceObjBean.bizList == null) {
            serviceObjBean.bizList = animalInfoList;
        } else {
            serviceObjBean.bizList.clear();
            serviceObjBean.bizList.addAll(animalInfoList);
        }
    }

    private void startLocation() {
        if (MyAMapLocation.resultLocation != null) {
            textLongitude = MyAMapLocation.resultLocation.longitude;
            textLatitude = MyAMapLocation.resultLocation.latitude;
            longitude.setText(String.valueOf(textLongitude));
            latitude.setText(String.valueOf(textLatitude));
        } else {
            relocation();
        }
    }

    private void relocation() {
        MyAMapLocation.getInstance().relocation(new LocationResult() {
            @Override
            public void result(boolean flag, LocationInfoBean locationInfoBean) {
                textLatitude = locationInfoBean.latitude;
                textLongitude = locationInfoBean.longitude;
                longitude.setText(String.valueOf(textLongitude));
                latitude.setText(String.valueOf(textLongitude));
            }

            @Override
            public void locationErr(String errMsg) {
                longitude.setText(getString(R.string.location_empty));
                latitude.setText(getString(R.string.location_empty));
                T.showSingleL(errMsg);
            }
        });
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        String type = inParam.get(EventBusConstant.TYPE).toString();
        if (FeedInfoEditActivity.TAG.equals(type)) {
            String key = inParam.get(EventBusConstant.ACTION_KEY).toString();
            BBizList animalInfo = (BBizList) inParam.get(EventBusConstant.ACTION_VALUE);
            switch (key) {
                case FeedInfoEditActivity.TYPE_ADD:
                    animalInfoList.add(animalInfo);
                    break;
                case FeedInfoEditActivity.TYPE_EDIT:
                    int editPosition = (int) inParam.get(IntentConstant.editPosition);//取出编辑的位置信息
                    animalInfoList.get(editPosition).copyBean(animalInfo);//替换该条目
                    break;
                case FeedInfoEditActivity.TYPE_DELETE:
                    int deletePosition = (int) inParam.get(IntentConstant.editPosition);
                    animalInfoList.remove(deletePosition);//删除某个条目
//                    Iterator<BBizList> iterator = animalInfoList.iterator();
//                    while (iterator.hasNext()) {
//                        BBizList bBizList = iterator.next();
//                        if (bBizList.biz_id.equals(animalInfo.biz_id)) {
//                            iterator.remove();
//                        }
//                    }
                    break;
            }
            fillBizView();
        } else if (MapLocationSearchActivity.TAG.equals(type)) {
            PoiItem item = (PoiItem) inParam.get(EventBusConstant.ACTION_KEY);
            mTvLocation.setText(item.getTitle());
            serviceObjBean.position_name = item.getTitle();
            textLongitude = item.getLatLonPoint().getLongitude();
            textLatitude = item.getLatLonPoint().getLatitude();
            serviceObjBean.latitude = String.valueOf(textLatitude);
            serviceObjBean.longitude = String.valueOf(textLongitude);
            longitude.setText(String.valueOf(textLongitude));
            latitude.setText(String.valueOf(textLatitude));
        }
    }
}
